﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace SiteFox.Base
{
    public class Page : System.Web.UI.Page
    {
        public const string SESSION_COOKIE_NAME = ".SESSION_COOKIE";
        public string SessionGuid { get; internal set; }
        
        public Page() : base()
        {
        }
        protected override void OnInit(EventArgs e)
        {
            if (!IsUserValidated() && Request.AppRelativeCurrentExecutionFilePath != "~/Login.aspx") 
            {
                Response.Redirect("~/Login.aspx");
            }
        }

        public bool IsUserValidated() 
        {
            bool _Result = false;
            this.SetSessionGuid();
            if (!this.SessionGuid.Trim().Length.Equals(0)) 
            {
                _Result = SiteFox.Business.Manager.User.UpdateSession(this.SessionGuid);
            }
            return _Result;
        }
        public bool Login(string _Login, string _Password)
        {
            SiteFox.Business.Model.User _User = SiteFox.Business.Manager.User.Validate(_Login, _Password);
            if (_User != null)
            {
                Guid _Guid = Guid.NewGuid();
                //==========================================================>>
                SiteFox.Business.Model.UserSession _Session = new Business.Model.UserSession();
                _Session.SessionGuid = _Guid.ToString();
                _Session.SessionTimeOut = SiteFox.Business.Data.WebConfig.GetSessionTimeOut();
                _Session.ID_User = _User.ID;
                _Session.LastSessionActiveDate = DateTime.Now;
                SiteFox.Business.Manager.User.AddSession(_Session);
                //==========================================================>>
                HttpCookie _Cookie = new HttpCookie(SESSION_COOKIE_NAME);
                _Cookie.Value = _Guid.ToString();
                this.SessionGuid = _Guid.ToString();
                Response.Cookies.Add(_Cookie);
                return true;
            }
            return false;
        }
        private void SetSessionGuid()
        {
            this.SessionGuid = "";
            HttpCookie _Cookie = Request.Cookies.Get(SESSION_COOKIE_NAME);
            if (_Cookie != null)
            {
                this.SessionGuid = _Cookie.Value;
            }
        }
        public SiteFox.Business.Model.User CurrentUser()
        {
            return SiteFox.Business.Manager.User.GetUser(SessionGuid);
        }
    }
}
